<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: chivoxsdk.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: chivoxsdk.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/**
 * ChiVoxSDK模块。&lt;br/>
 *
 * @module ChiVoxSDK
 * @author Don Li &lt;kai.li@chivox.com>
 * @licence
 * Copyright (c) 2017 - 2020 ChiVox Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import cfg             from './config.json';
import Utils           from './utils';
import PlayerBuilder   from './playerbuilder';
import RecorderBuilder from './recorderbuilder';

import ProgressBar     from './progressbar';
import ControlPanel    from './controlpanel';
import Dialog          from './dialog';

import EnScoreMap      from './lib/scoremap';
import EnWordScore     from './lib/score/enword';
import EnSentScore     from './lib/score/ensent';
import EnSentRec       from './lib/score/enrec';
import CnWordScore     from './lib/score/cnword';
import CnSentScore     from './lib/score/cnsent';

import Paragraph       from './lib/paragraph';
import StatusCode      from './lib/statuscode';

import swfobject       from './flash/swfobject';

import './default.css';

/**
 * 初始化ChiVoxSDK实例的默认值。&lt;br/>
 *
 * @name Default_ChiVoxSDK_Options
 * @global
 * @constant
 * @property {enum=} mode - 指定SDK的模式。可以指定为ChiVoxSDK.MODE.HTML5(默认值) 或 ChiVoxSDK.MODE.FLASH。
 * @property {string=} server - 指定SDK的评分服务器地址。默认值: ws://cloud.chivox.com
 * @property {string=} bak_server - 指定SDK的评分备份服务器地址。默认值: ''
 * @property {string} appKey - 指定SDK的开始评分所使用的appKey（由驰声提供）。**必填**
 * @property {string} sigurl - 指定SDK的开始评分前获取sig和timestamp的服务器地址（sig算法由驰声提供）。**必填**
 * @property {boolean=} recorder - 是否创建录音机。
 * @property {boolean=} player - 是否创建播放器。
 * @property {boolean=} playDing - 录音前，是否播放"Ding"音频。
 * @property {Object} data - 录音和播放音频所需的参数列表，如下：
 * @property {Object} data.audioUrl - 播放的音频URL。
 * @property {Object} data.serverParams - 录音所需的参数列表，下面描述几个基本的，更多请参考Example或联系驰声提供。
 * @property {Object} data.serverParams.coreType - 录音使用的内核类型。
 * @property {Object} data.serverParams.refText - 录音使用的参考文本。
 * @property {Object} data.serverParams.rank - 录音使用的分制。
 * @property {Object} data.serverParams.userId - 录音的终端用户ID，用于统计和分析用户更多的数据。
 * @property {callback} onInit - SDK初始化完成后的Callback调用。格式：(code, message) => {}
 * @property {callback} onError - SDK初始化或运行期间出错时的Callback调用。格式：(error) => {}
 * @property {callback} onConnectorStatusChange - SDK在与服务器的连接状态发生变化时的Callback调用。格式：(code, message) => {}
 * @property {callback} onAfterPlay - 开始播放音频后的Callback调用。格式：(element) => {}
 * @property {callback} onBeforeRecord - 开始录音前的Callback调用。格式：() => {}
 * @property {callback} onMicStatusChange - Flash模式下，麦克风状态发生变化时的Callback调用。格式：() => {}
 * @property {callback} onScore - 评分结果返回时的Callback调用。格式：(data) => {}
 * @property {callback} onInternalScore- 段落评分时实时push下来当前句子评测结果时的Callback调用。格式：(data) => {}
 * @property {callback} onScoreError - 评分结果返回时的Callback调用。格式：(errorType) => {}
 */
const _default_options = {
    mode: null,
    server: cfg.server,
    appKey: '',
    sigurl: '',
    recorder: true,
    player: true,
    playDing: true,
    data: {},
    onInit: (errno, err) => {}, //oninit handler
    onError: (err) => {}, //onerror handler
    onConnectorStatusChange: (code, message) => {
        console.debug('[ onConnectorStatusChange ]', code, message);
    },
};

let _ins_dialog = null;

/**
 * ChiVoxSDK类。&lt;br/>&lt;br/>
 *
 * 根据当前环境和配置，初始化并管理一个录音机，播放器。&lt;br/>
 * 支持2种模式：
 *   1. HTML5（默认，浏览器不支持的情况下会自动切换FLASH模式）。&lt;br/>
 *   2. FLASH模式。&lt;br/>
 * 支持边录边评，支持语音speex压缩。
 */
class ChiVoxSDK {
    /**
     * ChiVoxSDK模块提供的模式枚举对象。包含HTML5，FLASH两种。
     * @example
     * //使用模式FLASH：
     * var mode = ChiVoxSDK.MODE.FLASH;
     */
    static get MODE()           { return cfg.mode;        }
    /** ChiVoxSDK当前版本 */
    static get VERSION()        { return cfg.version;     }
    /** ChiVoxSDK的状态码类。 */
    static get StatusCode()     { return StatusCode;      }
    /** ChiVoxSDK的英文评分结果里音素与国际音标的MAP类。 */
    static get EnScoreMap()     { return EnScoreMap;      }
    /** ChiVoxSDK的英文单词评分结果类。 */
    static get EnWordScore()    { return EnWordScore;     }
    /** ChiVoxSDK的英文句子评分结果类。 */
    static get EnSentScore()    { return EnSentScore;     }
    /** ChiVoxSDK的英文有限分支评分结果类。 */
    static get EnSentRec()      { return EnSentRec;       }
    /** ChiVoxSDK的中文单词评分结果类。 */
    static get CnWordScore()    { return CnWordScore;     }
    /** ChiVoxSDK的中文句子评分结果类。 */
    static get CnSentScore()    { return CnSentScore;     }
    /** ChiVoxSDK的简单段落评分评分结果类。 */
    static get Paragraph()      { return Paragraph;       }
    /** ChiVoxSDK的状态对话框类。 */
    static get DIALOG()         { if (!_ins_dialog) _ins_dialog = new Dialog(); return _ins_dialog; } //设备和网络检测面板

    /**
     * ChiVoxSDK当前模式的人性化输出。
     *
     * @param {enum} mode - ChiVoxSDK.MODE.HTML5 或 ChiVoxSDK.MODE.FLASH的值。
     * @return {string} - "HTML5" | "FLASH" | "UNKNOWN"。
     */
    static mode(mode) {
        for (var prop in cfg.mode) {
            if (cfg.mode[prop] == mode)
                return prop;
        }
        return 'UNKNOWN';
    }

    /**
     * 创建一个ChiVoxSDK实例。
     *
     * @param {Object} options - 初始化参数。格式参见：{@link Default_ChiVoxSDK_Options}
     */
    constructor(options) {
        this.options = Utils.extend(options, _default_options, true);

        if (!options.hasOwnProperty('sigurl') || options.sigurl == "") {
            if (options.hasOwnProperty("onError")) { options.onError('param: sigurl is missing!'); }
        } else {
            let createPlayer = this.options.player;
            delete this.options.player;

            let createRecorder = this.options.recorder;
            delete this.options.recorder;

            this.progressbar  = new ProgressBar();      //录音进度条
            this.controlpanel = new ControlPanel();     //播放，回放，录音控制面板
            this.dialog       = ChiVoxSDK.DIALOG;

            this.dialog.close();

            if (!this.options.mode)
                this.options.mode = Utils.support_h5() ? cfg.mode.HTML5 : cfg.mode.FLASH;

            if (this.options.mode == cfg.mode.FLASH &amp;&amp; !ChiVoxSDK.detect_flash_plugin()) {
                this.dialog.open_flash_error();
            } else {
                let onInit    = this.options.onInit;

                if (this.options.mode == cfg.mode.FLASH) {
                    let loaded = 0,
                        need_load = (createPlayer ? 1 : 0) + (createRecorder ? 1 : 0);

                    this.options.onInit = () => {
                        loaded += 1;

                        if (loaded >= need_load)
                            onInit(0, 0);
                    };
                }

                if (createPlayer &amp;&amp; !this.player) {
                    this.player = ChiVoxSDK.createPlayer(this.options);
                    this.bindPlayerEvent();
                }

                if (createRecorder &amp;&amp; !this.recorder) {
                    this.recorder = ChiVoxSDK.createRecorder(this.options);
                    this.bindRecorderEvent();
                    this.bindReplayEvent();
                }

                if (this.options.mode != cfg.mode.FLASH) {
                    onInit(0, 0);
                }
            }
        }
    }

    /**
     * 检测当前浏览器是否能够正常使用Flash插件。
     * @return {boolean} - 是否能够正常使用Flash插件。
     */
    static detect_flash_plugin() {
        let ver = swfobject.getFlashPlayerVersion();
        return (ver &amp;&amp; ver.major != 0);
    }

    /**
     * 创建一个播放器。
     *
     * @param {Object} options - 创建播放器所需要的参数。
     * @return {Object} - Html5Player或FlashPlayer的实例。
     */
    static createPlayer(options) {
        return PlayerBuilder.build(options);
    }

    /**
     * 创建一个录音机。
     *
     * @param {Object} options - 创建录音机所需要的参数。
     * @return {Object} - Html5Recorder或FlashRecorder的实例。
     */
    static createRecorder(options) {
        return RecorderBuilder.build(options);
    }

    /** 为SDK实例绑定播放事件。*/
    bindPlayerEvent() {
        this.controlpanel.playOff();

        if (!this.controlpanel.ele_plays) {
            console.warn('not found any play button in aiPanell');
            return;
        }

        Utils.bind_mul(this.controlpanel.ele_plays, 'click', (e) => {
            let ele_play = e.target;

            if (!this.player.can_play) {
                this.controlpanel.playOff();
                return;
            }

            if (Utils.hasClass(ele_play, 'playOn')) {
                this.controlpanel.playOff(ele_play);
                this.player.reset();
            } else {
                this.resetStatus(ele_play, null, null);
                this.controlpanel.playOn();

                if (this.options.onBeforePlay) {
                    this.options.onBeforePlay(ele_play);
                }

                this.player.load({
                    url: this.options.data.audioUrl,
                    success: (code, mesage) => {
                        if (Utils.hasClass(ele_play, 'playOn')) {
                            this.player.play({
                                position: this.options.data.playPosition,
                                duration: this.options.playDuration,
                                onStart: (code, message) => {},
                                onStop: (code, message) => {
                                    this.controlpanel.playOff(ele_play);

                                    if (typeof this.options.onAfterPlay == 'function')
                                        this.options.onAfterPlay(ele_play);
                                }
                            });
                        }
                    }
                });
            }
        });
    }

    /** 为SDK实例绑定录音事件。*/
    bindRecorderEvent() {
        this.controlpanel.recordOff();

        Utils.bind_mul(this.controlpanel.ele_records, 'click', (e) => {
            let ele_record = e.target;

            if (Utils.hasClass(ele_record, 'recordDisabled')) { return; }
            if (Utils.hasClass(ele_record, 'recordOff')) {
                this.lastRecordId = "";
                ele_record.setAttribute('dataRecordId', '');

                if (this.options.onBeforeRecord) {
                    this.options.onBeforeRecord(ele_record);
                }

                this.resetStatus(null, ele_record, null);

                var duration = 200;
                var core_type = this.options.data.serverParams.coreType;
                if (this.options.data.duration)
                    duration = this.options.data.duration;
                else {
                    if (Utils.in_array(core_type, ['cn.word.score', 'cn.sent.score'])) {
                        var reftxt_cnt = this.options.data.serverParams.refText.replace(/^\s+|\s+$/g, '').split('-').length;
                        duration = 2000 + reftxt_cnt * 600;
                    } else if (Utils.in_array(core_type, ['en.word.score', 'en.sent.score'])) {
                        var reftxt_cnt = this.options.data.serverParams.refText.replace(/^\s+|\s+$/g, '').split(' ').length;
                        duration = 2000 + reftxt_cnt * 600;
                        //console.info('duration:', duration, reftxt_cnt, this.options.data.serverParams.refText);
                    }
                }

                this.recorder.record({
                    duration: duration,
                    playDing: this.options.playDing,
                    serverParams: this.options.data.serverParams,
                    onRecordIdGenerated: (code, message) => {
                        this.lastRecordId = message.recordId;
                        ele_record.setAttribute('dataRecordId', message.recordId); //TODO
                    },
                    onStart: () => {
                        this.controlpanel.recordOn(ele_record);
                        let idx = ele_record.getAttribute('dataIndex');
                        if (idx) idx = parseInt(idx);
                        this.progressbar.start(duration, idx);
                    },
                    onStop: (code, message) => {
                        this.controlpanel.recordOff(ele_record);
                        this.progressbar.stop();
                    },
                    onInternalScore: (code, message) => {
                        if (this.options.onInternalScore)
                            this.options.onInternalScore(message);
                    },
                    onScore: this.options.onScore,
                    onScoreError: this.options.onScoreError
                });
            } else { //stoprecord
                this.controlpanel.recordOff(ele_record);
                this.progressbar.stop();

                this.recorder.stopRecord();
            }
        });
    }

    /** 为SDK实例绑定录音回放事件。*/
    bindReplayEvent() {
        this.controlpanel.replayDisabled();

        Utils.bind_mul(this.controlpanel.ele_replays, 'click', (e) => {
            let ele_replay = e.target;

            if (!this.recorder.canRecord) {
                this.controlpanel.recordOff();
                this.controlpanel.replayDisabled();
                this.dialog.open();

                return;
            }

            if (!Utils.hasClass(ele_replay, 'replayDisabled')) {
                var record_id = this.lastRecordId;

                if (record_id != '') {
                    if (Utils.hasClass(ele_replay, 'replayOff')) {
                        this.resetStatus(null, null, ele_replay);
                        this.controlpanel.replayOn(ele_replay);

                        var params = {
                            recordId: record_id,
                            onStop: () => {
                                this.controlpanel.replayOff(ele_replay);
                            }
                        };

                        this.recorder.startReplay(params);
                    } else {
                        this.controlpanel.replayOff(ele_replay);
                        this.recorder.stopReplay();
                    }
                }
            }
        });
    }

    /** SDK实例重置当前状态。*/
    resetStatus(ele_play, ele_record, ele_replay) {
        this.player.reset();
        this.recorder.reset();
        this.progressbar.reset();
        this.controlpanel.playOff();
        this.controlpanel.recordOff();
        this.controlpanel.replayOff();

        if (typeof ele_play == 'undefined' &amp;&amp; typeof ele_record == 'undefined' &amp;&amp; typeof ele_replay == 'undefined') {
            this.controlpanel.replayDisabled();
        }
    }

    /** SDK实例更新或设置data参数。 格式参见：{@link Default_ChiVoxSDK_Options}*/
    setData(data) {
        this.resetStatus();
        this.options.data = data;
    }
}

window.ChiVoxSDK = ChiVoxSDK;
export default ChiVoxSDK
</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-ChiVoxSDK.html">ChiVoxSDK</a></li><li><a href="module-ChiVoxSDK_flash.html">ChiVoxSDK/flash</a></li><li><a href="module-ChiVoxSDK_html5.html">ChiVoxSDK/html5</a></li><li><a href="module-ChiVoxSDK_lib.html">ChiVoxSDK/lib</a></li><li><a href="module-ChiVoxSDK_Paragraph.html">ChiVoxSDK/Paragraph</a></li><li><a href="module-ChiVoxSDK_score.html">ChiVoxSDK/score</a></li></ul><h3>Classes</h3><ul><li><a href="module-ChiVoxSDK_flash.FlashPlayer.html">FlashPlayer</a></li><li><a href="module-ChiVoxSDK_flash.FlashRecorder.html">FlashRecorder</a></li><li><a href="module-ChiVoxSDK_html5.Html5Player.html">Html5Player</a></li><li><a href="module-ChiVoxSDK_html5.Html5Recorder.html">Html5Recorder</a></li><li><a href="module-ChiVoxSDK_html5-VolumeBar.html">VolumeBar</a></li><li><a href="module-ChiVoxSDK_lib-EnScoreMap.html">EnScoreMap</a></li><li><a href="module-ChiVoxSDK_lib-StatusCode.html">StatusCode</a></li><li><a href="module-ChiVoxSDK_Paragraph-Paragraph.html">Paragraph</a></li><li><a href="module-ChiVoxSDK_score-Char.html">Char</a></li><li><a href="module-ChiVoxSDK_score-CnSentScore.html">CnSentScore</a></li><li><a href="module-ChiVoxSDK_score-CnWordScore.html">CnWordScore</a></li><li><a href="module-ChiVoxSDK_score-EnSentRec.html">EnSentRec</a></li><li><a href="module-ChiVoxSDK_score-EnSentScore.html">EnSentScore</a></li><li><a href="module-ChiVoxSDK_score-EnWordScore.html">EnWordScore</a></li><li><a href="module-ChiVoxSDK_score-Phone.html">Phone</a></li><li><a href="module-ChiVoxSDK_score-Word.html">Word</a></li><li><a href="module-ChiVoxSDK-ChiVoxSDK.html">ChiVoxSDK</a></li><li><a href="module-ChiVoxSDK-ControlPanel.html">ControlPanel</a></li><li><a href="module-ChiVoxSDK-Dialog.html">Dialog</a></li><li><a href="module-ChiVoxSDK-PlayerBuilder.html">PlayerBuilder</a></li><li><a href="module-ChiVoxSDK-ProgressBar.html">ProgressBar</a></li><li><a href="module-ChiVoxSDK-RecorderBuilder.html">RecorderBuilder</a></li></ul><h3>Namespaces</h3><ul><li><a href="public.html">public</a></li><li><a href="Utils.html">Utils</a></li></ul><h3>Global</h3><ul><li><a href="global.html#Default_ChiVoxPlayer_Options">Default_ChiVoxPlayer_Options</a></li><li><a href="global.html#Default_ChiVoxRecorder_Options">Default_ChiVoxRecorder_Options</a></li><li><a href="global.html#Default_ChiVoxSDK_Options">Default_ChiVoxSDK_Options</a></li><li><a href="global.html#Default_Paragraph_Options">Default_Paragraph_Options</a></li><li><a href="global.html#get_sig">get_sig</a></li><li><a href="global.html#tts">tts</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Thu Sep 21 2017 16:38:41 GMT+0800 (CST)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
